#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#include<stdlib.h>
void MerseryNonR(int* arr, int n)
{
	int gap = 1; int* temp = (int*)malloc(n*sizeof(int));
	while(gap < n)
	{
		int i = 0;
		for (i = 0; i < n; i += 2 * gap)
		{
			
			//[i i+gap-1]  [i+gap i+2*gap-1]
			int begin1 = i; int end1 = i + gap - 1;
			int begin2 = i + gap; int end2 = i + 2 * gap - 1;
			if (begin2 >= n)
				break;
			if (end2 >= n)
				end2 = n - 1;
			int index = i;
			while (begin1 <= end1&&begin2 <= end2)
			{
				if (arr[begin1] < arr[begin2])
					temp[index++] = arr[begin1++];
				else
					temp[index++] = arr[begin2++];
			}
			while (begin1<=end1)
				temp[index++] = arr[begin1++];
			while (begin2<=end2)
				temp[index++] = arr[begin2++];
			int j = 0;
			for (j = 0; j <= end2; j++)
				arr[j] = temp[j];
		}
		gap *= 2;
	}
}
int main()
{
	int arr[] = { 1, 5, 4, 6, 8, 7, 9 ,5};
	int len = sizeof(arr) / sizeof(arr[0]);
	MerseryNonR(arr, len);
	int i = 0;
	for (i = 0; i < len; i++)
	{
		printf("%d ", arr[i]);
	}
	printf("\n");
	return 0;
}